/*
 * Copyright 2009-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.googlecode.viewt.core;

import org.googlecode.viewt.core.exception.BeanCreateException;
import org.googlecode.viewt.core.exception.ContextInitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringContextHelper {
	public static final String SPRING_CONFIG_FILE_PATTERN = "classpath*:**/*.spc.xml";
	protected final Logger logger;
	private static ApplicationContext context = null;

	private static String lockObj = "LOCK";

	public SpringContextHelper() {
		this.logger = LoggerFactory.getLogger(super.getClass());
	}

	public static ApplicationContext getContext() throws ContextInitException {
		synchronized (lockObj) {
			if (null == context) {
				Logger logger = LoggerFactory.getLogger(SpringContextHelper.class);

				if (logger.isDebugEnabled())
					logger
							.debug("Begin to initialize spring application context");
				try {
					context = new ClassPathXmlApplicationContext(
							"classpath*:**/*.spc.xml");
				} catch (BeansException beanEx) {
					logger.error("create spring application context fail",
							beanEx);
					throw new ContextInitException(
							"create spring application context fail", beanEx);
				}

				if (logger.isDebugEnabled()) {
					logger
							.debug("Initialize spring application context successful, config file pattern:classpath*:**/*.spc.xml");
				}
			}
		}
		return context;
	}

	public static Object getBean(String beanName) throws ContextInitException,
			BeanCreateException {
		Logger logger = LoggerFactory.getLogger(SpringContextHelper.class);
		if (logger.isDebugEnabled()) {
			logger.debug("Begin to get spring bean:" + beanName);
		}
		Object result = null;
		try {
			ApplicationContext context = getContext();
			result = context.getBean(beanName);
		} catch (BeansException beanEx) {
			logger.error("Get spring bean:" + beanName + " fail", beanEx);
			throw new BeanCreateException("Get spring bean:" + beanName
					+ " fail", beanEx);
		}

		if (logger.isDebugEnabled())
			logger.debug("Get spring bean:" + beanName + " succeed");
		return result;
	}
}